package app.action;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

import org.apache.log4j.Logger;

public class StartServer extends Thread {
	private final static Logger logger = Logger.getLogger(StartServer.class);
	private Socket socket;
	private ServerSocket serverSocket;
	private ServerThreadHandler serverThreadHandler;
	private Vector<ServerThreadHandler> serverThreadHandlers = new Vector<>();
	private int threadID = 1; // Server-user will take ID = 0
	private boolean serverStarted = true;

	protected User me;

	public StartServer(int port) throws IOException {
		serverSocket = new ServerSocket(port);
		this.me = new User(0, "SERVER");
	}

	@Override
	public void run() {
		try {
			logger.info("Wait for a request from client ..");
			while (serverStarted) {
				socket = serverSocket.accept();
				serverThreadHandler = new ServerThreadHandler(this, socket, threadID++);
				serverThreadHandler.start();
			}
		}catch (IOException e) {
			logger.error(e.getMessage(), e.getCause());
		}finally {
			try {
				serverSocket.close();
			}catch (IOException e) {
				logger.error(e.getMessage(), e.getCause());
			}
		}
	}

	protected Vector<ServerThreadHandler> getServerThreadHandlers() {
		return serverThreadHandlers;
	}

	public int getNumberOfOnline() {
		return (getServerThreadHandlers().size());
	}
}
